package org.setec.utils.xml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class XMLUtils {

    public static String findFirst(String text, String regexp) {
        Matcher matcher = Pattern.compile(regexp, Pattern.DOTALL).matcher(text);
        while (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

    public static String normalizeXML(String xml) {
        xml = xml.trim();
        xml = xml.replaceAll("  |\n|\r", "");
        xml = xml.replaceAll("> <", "><");
        xml = xml.replaceAll("<\\?.*?>", "");
        return xml;
    }

    public static Map parseAttributes(String attributesContent){
        Map result = new HashMap();
        if( attributesContent!=null && attributesContent.length()>0 ){
            String[] attributes = attributesContent.split(" ");
            for( int i = 0; i<attributes.length; i++ ){
                String[] pair = attributes[i].split("=");
                pair[1] = pair[1].replaceAll("^\"|\"$", "");
                result.put(pair[0], pair[1]);
            }
        }
        return result;
    }

    public static List findAll(String text, String regExp){
        List result = new ArrayList();
        Matcher matcher = Pattern.compile(regExp, Pattern.DOTALL).matcher(text);
        while (matcher.find()) {
            result.add(matcher.group());
        }
        return result;
    }
}
